package com.hl.ruoyilkshop.controller;

import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.hl.ruoyilkshop.domain.BusinessUserRelation;
import com.hl.ruoyilkshop.service.IBusinessUserRelationService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 商家用户关联Controller
 * 
 * @author ruoyi
 * @date 2025-08-08
 */
@RestController
@RequestMapping("/relation")
public class BusinessUserRelationController extends BaseController
{
    @Autowired
    private IBusinessUserRelationService businessUserRelationService;

    /**
     * 查询商家用户关联列表
     */
    @RequiresPermissions("lkshop:relation:list")
    @GetMapping("/list")
    public TableDataInfo list(BusinessUserRelation businessUserRelation)
    {
        startPage();
        List<BusinessUserRelation> list = businessUserRelationService.selectBusinessUserRelationList(businessUserRelation);
        return getDataTable(list);
    }

    /**
     * 获取当前用户的商家信息
     */
    @GetMapping("/myBusiness")
    public AjaxResult getMyBusiness()
    {
        Long userId = SecurityUtils.getUserId();
        BusinessUserRelation defaultBusiness = businessUserRelationService.selectDefaultBusinessByUserId(userId);
        if (defaultBusiness != null) {
            return success(defaultBusiness);
        } else {
            // 如果没有默认商家，返回第一个关联的商家
            List<BusinessUserRelation> businessList = businessUserRelationService.selectBusinessListByUserId(userId);
            if (!businessList.isEmpty()) {
                return success(businessList.get(0));
            }
            return error("未找到关联的商家信息");
        }
    }

    /**
     * 获取当前用户的所有商家信息
     */
    @GetMapping("/myBusinessList")
    public AjaxResult getMyBusinessList()
    {
        Long userId = SecurityUtils.getUserId();
        List<BusinessUserRelation> businessList = businessUserRelationService.selectBusinessListByUserId(userId);
        return success(businessList);
    }

    /**
     * 调试接口 - 获取当前用户ID和商家关联信息
     */
    @GetMapping("/debug")
    public AjaxResult debug()
    {
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        
        // 查询默认商家关联
        BusinessUserRelation defaultBusiness = businessUserRelationService.selectDefaultBusinessByUserId(userId);
        
        // 查询所有商家关联
        List<BusinessUserRelation> allBusinessList = businessUserRelationService.selectBusinessListByUserId(userId);
        
        // 查询所有关联（不限制状态）
        BusinessUserRelation queryParam = new BusinessUserRelation();
        queryParam.setUserId(userId);
        List<BusinessUserRelation> allRelations = businessUserRelationService.selectBusinessUserRelationList(queryParam);
        
        return success()
            .put("userId", userId)
            .put("username", username)
            .put("defaultBusiness", defaultBusiness)
            .put("allBusinessList", allBusinessList)
            .put("allRelations", allRelations)
            .put("defaultBusinessCount", defaultBusiness != null ? 1 : 0)
            .put("allBusinessListCount", allBusinessList.size())
            .put("allRelationsCount", allRelations.size());
    }

    /**
     * 导出商家用户关联列表
     */
    @RequiresPermissions("lkshop:relation:export")
    @Log(title = "商家用户关联", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BusinessUserRelation businessUserRelation)
    {
        List<BusinessUserRelation> list = businessUserRelationService.selectBusinessUserRelationList(businessUserRelation);
        ExcelUtil<BusinessUserRelation> util = new ExcelUtil<BusinessUserRelation>(BusinessUserRelation.class);
        util.exportExcel(response, list, "商家用户关联数据");
    }

    /**
     * 获取商家用户关联详细信息
     */
    @RequiresPermissions("lkshop:relation:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(businessUserRelationService.selectBusinessUserRelationById(id));
    }

    /**
     * 新增商家用户关联
     */
    @RequiresPermissions("lkshop:relation:add")
    @Log(title = "商家用户关联", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BusinessUserRelation businessUserRelation)
    {
        return toAjax(businessUserRelationService.insertBusinessUserRelation(businessUserRelation));
    }

    /**
     * 修改商家用户关联
     */
    @RequiresPermissions("lkshop:relation:edit")
    @Log(title = "商家用户关联", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BusinessUserRelation businessUserRelation)
    {
        return toAjax(businessUserRelationService.updateBusinessUserRelation(businessUserRelation));
    }

    /**
     * 删除商家用户关联
     */
    @RequiresPermissions("lkshop:relation:remove")
    @Log(title = "商家用户关联", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(businessUserRelationService.deleteBusinessUserRelationByIds(ids));
    }
}
